<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Product;
use App\Services\Wechat\WechatPaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    /**
     * 处理微信支付回调
     */
    public function notify(Request $request)
    {
        Log::info('收到微信支付回调请求', [
            'headers' => $request->headers->all(),
            'body' => $request->getContent()
        ]);

        try {
            $paymentService = new WechatPaymentService();
            
            // 处理回调并获取解密后的数据
            $notifyData = $paymentService->handleNotify($request);
            
            Log::info('微信支付回调数据解析成功', $notifyData);
            
            // 检查交易状态
            if ($notifyData['trade_state'] === 'SUCCESS') {
                // 查找订单
                $order = Order::where('order_number', $notifyData['out_trade_no'])->first();
                
                if (!$order) {
                    Log::error('订单未找到', ['order_number' => $notifyData['out_trade_no']]);
                    return $this->failResponse('订单未找到');
                }
                
                // 检查订单是否已经支付过（防止重复回调）
                if ($order->payment_status === Order::PAYMENT_STATUS_PAID) {
                    Log::info('订单已支付，忽略重复回调', ['order_number' => $notifyData['out_trade_no']]);
                    return $this->successResponse();
                }
                
                // 验证金额是否一致
                $totalAmount = $notifyData['amount']['total'];
                if ($order->total_price * 100 != $totalAmount) { // 微信金额单位是分
                    Log::error('订单金额不匹配', [
                        'order_number' => $notifyData['out_trade_no'],
                        'order_amount' => $order->total_price * 100,
                        'notify_amount' => $totalAmount
                    ]);
                    return $this->failResponse('订单金额不匹配');
                }
                
                // 使用事务确保数据一致性
                DB::transaction(function () use ($order, $notifyData) {
                    // 更新订单状态
                    $order->markAsPaid(
                        Order::PAYMENT_METHOD_WECHAT,
                        $notifyData['transaction_id']
                    );
                    
                    // 扣减订单商品库存
                    $this->deductProductStock($order);
                });
                
                Log::info('订单支付成功，已更新订单状态并扣减库存', [
                    'order_number' => $notifyData['out_trade_no'],
                    'transaction_id' => $notifyData['transaction_id']
                ]);
                
                return $this->successResponse();
            } else {
                Log::warning('支付状态异常', [
                    'trade_state' => $notifyData['trade_state'],
                    'out_trade_no' => $notifyData['out_trade_no']
                ]);
                return $this->successResponse(); // 即使支付失败也要返回成功，避免微信重复推送
            }
            
        } catch (\Exception $e) {
            Log::error('微信支付回调处理异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return $this->failResponse($e->getMessage());
        }
    }
    
    /**
     * 扣减订单商品库存
     */
    private function deductProductStock($order)
    {
        // 加载订单项及关联的商品
        $order->load('items.product');
        
        foreach ($order->items as $item) {
            // 检查商品是否存在
            if ($item->product) {
                // 检查库存是否足够
                if ($item->product->stock < $item->quantity) {
                    Log::warning('商品库存不足', [
                        'product_id' => $item->product->id,
                        'product_name' => $item->product->name,
                        'current_stock' => $item->product->stock,
                        'required_quantity' => $item->quantity
                    ]);
                    // 可以选择抛出异常或记录警告但继续处理
                    // 这里我们记录警告但继续处理
                }
                
                // 扣减库存
                $item->product->decrement('stock', $item->quantity);
                
                // 增加销售数量
                $item->product->increment('sales_count', $item->quantity);
                
                Log::info('商品库存已扣减', [
                    'product_id' => $item->product->id,
                    'product_name' => $item->product->name,
                    'deducted_quantity' => $item->quantity,
                    'new_stock' => $item->product->stock - $item->quantity
                ]);
            }
        }
    }
    
    /**
     * 返回成功响应
     */
    private function successResponse()
    {
        return response()->json([
            'code' => 'SUCCESS',
            'message' => '成功'
        ], 200);
    }
    
    /**
     * 返回失败响应
     */
    private function failResponse($message = '处理失败')
    {
        return response()->json([
            'code' => 'FAIL',
            'message' => $message
        ], 400);
    }
}